<?php
/**
 * 农商行在线接口类
 */
defined('IN_NWIDC') or exit('Access Invalid!');
class_exists('MerchantConfig') or require(dirname(__FILE__).'/ebusclient/core/MerchantConfig.php');
class_exists('Result') or require_once (dirname(__FILE__).'/ebusclient/Result.php');
class_exists('QueryOrderRequest') or require_once (dirname(__FILE__).'/ebusclient/QueryOrderRequest.php');
class_exists('Json') or require (dirname(__FILE__) . '/ebusclient/core/Json.php');
class abcpay{
    /*
     * 版本号
     * */
    private $abc_version = 'V3.0.0';
    /*
     * 商户序号
     * */
    private $MerchantNo = 1;
    /*
     * 商户账号
     * */
    private $MerchantID = '';
    /**
     * 农商行在线网关
     *
     * @var string
     */
    private $gateway   = 'https://pay.abchina.com/ebus/trustpay/ReceiveMerchantTrxReqServlet';
    /**
     * 支付接口配置信息
     *
     * @var array
     */
    private $request;
    /**
     * 订单信息
     * @var array
     */
    private $order;
    /**
     * 对账号
     * @var string
     */
    private $tradeno;
    /**
     * 订单其他信息
     * @var array
     */
    private $orderitems;

    /**
     * 返回报文实例化后对象
     */
    private $tTrxResponse;
    /**
     * 支付结果
     * return boolean
     */
    private $pay_result = false;

    public function __construct($payment_info,$order_info){
        $this->abcpay($payment_info,$order_info);
    }
    public function abcpay($payment_info = array(),$order_info = array()){

        $payment_conf = parse_ini_file(dirname(__FILE__).'/ebusclient/TrustMerchant.ini');
        $this->MerchantID = $payment_conf['MerchantID'];

        if(!empty($payment_info) and !empty($order_info)){
            $this->request	= $payment_info;
            $this->order	= $order_info;
        }
    }
    /**
     * 支付表单
     *
     */
    public function get_payurl(){
        $order_info = Model('order')->getOrderInfo([
            'order_id' => $this->order['order_list'][0]['order_id']
        ], ['order_goods']);

        $aMerchantNo = $this->MerchantNo;
        $abc_order = array (
            "PayTypeID" =>  "ImmediatePay",
            "OrderNo" => $order_info['order_sn'],
            "OrderAmount" => $order_info['order_amount'],
            "Fee" => "",
            "CurrencyCode" => "156",
            "ReceiverAddress" => "",
            "InstallmentMark" => "0",
            "OrderDesc" => "",
            "OrderDate" => date("Y/m/d",$order_info['add_time']),
            "OrderTime" => date("H:i:s",$order_info['add_time']),
            "CommodityType" => "0202",
            "remark1"   => $this->order['order_type']
        );

        //商品信息
        foreach($order_info['extend_order_goods'] as $k => $v){
            $this->orderitems[]['ProductName'] = $v['goods_name'];
        }

        //3、生成支付请求对象
        $abc_request = array(
            "TrxType" => "PayReq",
            "PaymentType" => '6',//设定支付类型
            "PaymentLinkType" => "1",//设定支付接入方式
            "ReceiveAccount" => "", //设定收款方账号
            "ReceiveAccName" => "",//设定收款方户名
            "NotifyType" => "1",//设定通知方式
            "ResultNotifyURL" => "http://10.190.9.49:8050/WebSite/netBank/zh_CN/Entrance/OrderPayAction.ebf",//设定通知URL地址
            "MerchantRemarks" => "QGHG|".$order_info['receiver_name'].'|'.$order_info['idcard']."#".$this->order['pay_sn']."#".$order_info['order_sn']."#".$this->order['order_type']."#abcpay",//设定附言
            "IsBreakAccount" => "0", //设定交易是否分账
        );

        $js = '"Order":' . (json_encode($abc_order));
        $js = substr($js, 0, -1);
        $js = $js . ',"OrderItems":[';
        $count = count($this->orderitems, COUNT_NORMAL);
        for ($i = 0; $i < $count; $i++) {
            $js = $js . json_encode($this->orderitems[$i]);
            if ($i < $count -1) {
                $js = $js . ',';
            }
        }
        $js = $js . ']}}';
        $tMessage = json_encode($abc_request);
        $tMessage = substr($tMessage, 0, -1);
        $tMessage = $tMessage . ',' . $js;

        //拼接为完整报文
        $tMessage = $this->composeRequestMessage($tMessage);
        //报文签名
        $tMessage = MerchantConfig::signMessage($aMerchantNo, $tMessage);

        $opts = array(
            'http' => array(
                'method' => 'POST',
                'user_agent' => 'TrustPayClient '.$this->abc_version,
                'protocol_version' => 1.0,
                'header' => array('Content-Type: text/html', 'Accept: */*'),
                'content' => $tMessage
            ),
            'ssl' => array(
                'verify_peer' => false
            )
        );
        $context = stream_context_create($opts);
        $tResponseMessage = file_get_contents($this->gateway, false, $context);

        $this->tTrxResponse = new Json($tResponseMessage);

        MerchantConfig::verifySign($this->tTrxResponse);

        if(!$this->tTrxResponse)
        {
            throw new TrxException(TrxException::TRX_EXC_CODE_1205, TrxException::TRX_EXC_MSG_1205, '返回报文为空！');
        }
        if($this->tTrxResponse->isSuccess()){
            //请求成功，验证通过，返回支付链接
            $PaymentURL = $this->tTrxResponse->GetValue("PaymentURL");
            return $PaymentURL;
        }else if($this->tTrxResponse->getReturnCode() == 2306 ){
            echo "<!doctype html>
                <html lang=\"en\">
                <head>
                    <meta charset=\"UTF-8\">
                </head>
                <body>
                    <script>
                        alert(\"提交失败,".$this->tTrxResponse->getErrorMessage().",请通过历史记录在首次打开的支付页面进行支付！\");
                        history.go(-1);
                    </script>
                </body>
                </html>";
            exit;
        }
        else {
            echo "<!doctype html>
                <html lang=\"en\">
                <head>
                    <meta charset=\"UTF-8\">
                </head>
                <body>
                <script>
                    alert(\"提交失败,Error code:".$this->tTrxResponse->getReturnCode()."\");
                    history.go(-1);
                </script>
                </body>
                </html>";
           exit;
        }

    }

    /*
     * 返回地址验证
     * */
    public function notify_verify(){
        $tResult = new Result();
        //取得MSG参数，并利用此参数值生成验证结果对象
        $tResponse = $tResult->init($_POST['MSG']);
        if ($tResponse->isSuccess()) {
            //向支付平台发送验证请求
            $QueryRequest = new QueryOrderRequest();
            $QueryRequest->request["PayTypeID"] = 'ImmediatePay'; //设定交易类型
            $QueryRequest->request["OrderNo"] = $this->order['order_list'][0]['order_sn']; //设定订单编号 （必要信息）
            $QueryRequest->request["QueryDetail"] = "false"; //设定查询方式

            $QueryResponse = $QueryRequest->postRequest();

            if($QueryResponse->isSuccess()){
                if($QueryResponse->getReturnCode() == '0000'){
                    //**********Result  支付成功
                    $this->tradeno = $tResponse->getValue('iRspRef');
                    $this->pay_result = true;
                    return true;
                }else{
                    print('支付失败');
                    return false;
                }
            }else{
                //订单为空
                print ("<br>ReturnCode   = [" . $tResponse->getReturnCode() . "]<br>");
                print ("ErrorMessage = [" . $tResponse->getErrorMessage() . "]<br>");
                return false;
            }
        } else {
            //失败
            print ("<br>ReturnCode   = [" . $tResponse->getReturnCode() . "]<br>");
            print ("ErrorMessage = [" . $tResponse->getErrorMessage() . "]<br>");
            return false;
        }
    }

    public function return_verify(){
        return $this->notify_verify();
    }

    /**
     * 组成完整交易报文
     * @param $aMessage 交易报文
     * @return 完整交易报文
     */
    private function composeRequestMessage($aMessage) {
        $tMessage = "{\"Version\":\"".$this->abc_version."\",\"Format\":\"JSON\",\"Merchant\":" . "{\"ECMerchantType\":\"" . "EBUS" . "\",\"MerchantID\":\"".$this->MerchantID."\"}," . "\"TrxRequest\":" . $aMessage . "}";
        return $tMessage;
    }

    /**
     * 取得订单支付状态，成功或失败
     * @return array
     */
    public function getPayResult($parms){
        return $this->pay_result;
    }

    /*
     * 获取交易流水单号
     * */
    public function getTradeNo(){
        return $this->tradeno;
    }
    public function __get($name){
        return $this->$name;
    }
}
